#include <iostream>

#include "threadpool1.h"
ThreadPool::ThreadPool()
    : thread_num_(std::thread::hardware_concurrency()), stop_(false) {}
ThreadPool::ThreadPool(int thread_num) : thread_num_(thread_num), stop_(false) {
  std::cout << thread_num << std::endl;
  for (int i = 0; i < thread_num; i++) {
    thread_vec_.emplace_back(std::thread(&ThreadPool::ThreadFunc, this));
  }
}
ThreadPool::~ThreadPool() {
  stop_ = true;
  empty_cond_.notify_all();
  for (auto& t : thread_vec_) {
    t.join();
  }
}

void ThreadPool::AddTask(Task&& f) {
  std::unique_lock<std::mutex> ul(mtx_);
  while (!task_que_.size() && !stop_) full_cond_.wait(ul);
  if (stop_) {
    std::cout << "任务提交失败" << std::endl;
    return;
  }
  task_que_.push(f);
  empty_cond_.notify_one();
}

void ThreadPool::ThreadFunc() {
  Task f;
  while (1) {
    {
      std::unique_lock<std::mutex> ul(mtx_);
      while (task_que_.size() == 0 && !stop_) empty_cond_.wait(ul);
      if (stop_ && task_que_.size() == 0) {
        std::cout << std::this_thread::get_id() << "结束" << std::endl;
        return;
      }
      f = std::move(task_que_.front());
      task_que_.pop();
    }
    full_cond_.notify_one();
    std::cout << std::this_thread::get_id() << "执行任务" << std::endl;
    f();
  }
}